﻿using Sharp.Events;
using Sharp.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using Sharp.Domain.PlatformBoundedContext.ConfigModule;

namespace Sharp.Domain.PlatformBoundedContext.UserModule.Events
{
    /// <summary>
    /// 发送邮件
    /// </summary>
    [Async]
    public class SendEMailHandler :
        IEventHandler<ResetPasswordEventData>,
        IEventHandler<SuccessfulRegistrationEventData>
    {
        private static readonly SmtpClient Smtp;
        static SendEMailHandler()
        {
            var config = new PlatformInfo();
            Smtp = new SmtpClient
            {
                Credentials = new NetworkCredential(config.EMailConfig.LoginName, config.EMailConfig.Password),
                Port = 25,
                Host = config.EMailConfig.SmtpServer,
                EnableSsl = false
            };
        }
        public SendEMailHandler()
        {

        }
        public void Handle(SuccessfulRegistrationEventData evt)
        {
            SendEMail(evt.Subject, evt.Body, evt.Email, evt.FromEMail);
        }

        public void Handle(ResetPasswordEventData evt)
        {
            SendEMail(evt.Subject, evt.Body, evt.Email, evt.FromEMail);
        }

        /// <summary>
        /// 发送电邮
        /// </summary>
        /// <param name="subject">主题</param>
        /// <param name="body">正文</param>
        /// <param name="toEMail">发送至</param>
        /// <param name="fromEMail">发邮信箱</param>
        /// <returns></returns>
        private Result SendEMail(string subject, string body, string toEMail, string fromEMail)
        {
            var res = new Result();

            MailMessage mailMsg = new MailMessage
            {
                From = new MailAddress(fromEMail)
            };

            mailMsg.To.Add(toEMail);
            mailMsg.Subject = subject;
            mailMsg.Body = body;

            mailMsg.BodyEncoding = Encoding.UTF8;
            mailMsg.IsBodyHtml = true;
            mailMsg.Priority = MailPriority.Normal;

            Smtp.Send(mailMsg);

            res.Message = "邮件已经发出。";
            return res;
        }
    }
}